package cn.tedu.luban.settle.main.service;

import cn.tedu.luban.account.api.AccountApi;
import cn.tedu.luban.account.protocol.param.AccountPayParam;
import cn.tedu.luban.order.protocol.dto.OrderMessageDTO;
import cn.tedu.luban.settle.main.converter.SettleConverter;
import cn.tedu.luban.settle.main.repository.SettleRepository;
import cn.tedu.luban.settle.protocol.param.SettleBillParam;
import com.tedu.inn.protocol.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class SettleService {

    @Autowired
    private SettleRepository settleRepository;
    @Autowired
    private SettleConverter settleConverter;
    @Autowired
    private AccountApi accountApi;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void settle(OrderMessageDTO orderMessageDTO) throws BusinessException {
        // 考虑幂等 先查询订单是否已经存在账单
        String orderNo = orderMessageDTO.getOrderNo();
        if(StringUtils.isEmpty(orderNo)){
            log.error("结算失败,订单消息为空");
            return;
        }
        // 1. 账单是否存在
        Long total = settleRepository.countSettleBillByOrderNo(orderNo);
        if (total>0) {
            throw new BusinessException("1002","账单存在");
        }

        // 2.利用订单数据,生成和创建账单:师傅账单 平台账单
        List<SettleBillParam> params = settleConverter.dto2params(orderMessageDTO);
        // 第一个元素 师傅账单, 第二个元素 平台账单
        settleRepository.batchSave(params);

        // 3. 从账单中找到师傅账单,根据结算数据,给师傅进行打款操作
        SettleBillParam workerBill = params.get(0);
        AccountPayParam accountPayParam = new AccountPayParam();
        accountPayParam.setUserId(workerBill.getWorkerId());
        accountPayParam.setOrderNo(workerBill.getOrderNo());
        accountPayParam.setTotalAmount(workerBill.getTotalAmount());
        accountApi.mockPayment(accountPayParam);

        // 4. 发送消息
        Message<String> message = MessageBuilder.withPayload(orderNo).build();
        rocketMQTemplate.syncSend("order_complete_topic",message);

    }

}
